package org.example.database_course_design.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.example.database_course_design.entity.DTO.cardIDAndPass;
import org.example.database_course_design.entity.DTO.CardUpdateDTO;
import org.example.database_course_design.entity.PO.Cardinfo;
import org.example.database_course_design.entity.PO.Deposit;
import org.example.database_course_design.entity.Result;
import org.example.database_course_design.entity.PO.Userinfo;
import org.example.database_course_design.mapper.UserinfoMapper;
import org.example.database_course_design.mapper.CardinfoMapper;
import org.example.database_course_design.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private UserinfoMapper userinfoMapper;

    @Autowired
    private CardinfoMapper cardinfoMapper;

    @PostMapping("/login")
    @Operation(
            summary = "管理员登录",
            parameters = {
                    @Parameter(name = "username", description = "用户名"),
                    @Parameter(name = "password", description = "密码")
            }
    )
    public Result login(String username, String password) {
        Userinfo u = adminService.login(username, password);
        if(u == null) return Result.error("500", "登录失败");
        return Result.success(u);
    }

    @PostMapping("/user/signup")
    @Operation(
            summary = "客户注册",
            parameters = {
                    @Parameter(name = "Pid", description = "证件号码"),
                    @Parameter(name = "CustomerName", description = "客户姓名"),
                    @Parameter(name = "Telephone", description = "手机号码"),
                    @Parameter(name = "Address", description = "地址")
            }
    )
    public Result signup(@RequestBody Map<String, Object> map) {
        Userinfo u = adminService.signup(map);
        return u == null? Result.error("500", "注册失败") : Result.success(u);
    }

    @DeleteMapping("/user/delete")
    @Operation(
            summary = "客户删除",
            parameters = {
                    @Parameter(name = "pid", description = "证件号码")
            }
    )
    public Result delete(@RequestParam String pid) {
        boolean res = adminService.removeById(pid);
        return res? Result.success(null): Result.error("500", "删除失败");
    }

    @PutMapping("/user/update")
    @Operation(
            summary = "客户消息更新"
    )
    public Result update(@RequestBody Userinfo u) {
        u = adminService.update(u);
        return u == null? Result.error("500", "更新失败"): Result.success(u);
    }

    @GetMapping("/user/getList")
    @Operation(
            summary = "客户列表查询",
            parameters = {
                    @Parameter(name = "nums", description = "页码"),
                    @Parameter(name = "size", description = "每页数量")
            }
    )
    public Result getCustomerList(@RequestParam(defaultValue = "0") Integer nums, @RequestParam(defaultValue = "10") Integer size) {
        return Result.success(adminService.getCustomerList(nums, size));
    }

    @GetMapping("/user/toCSV")
    @Operation(summary = "客户列表导出")
    public ResponseEntity<FileSystemResource> CustomerToCSV() throws IOException {
        String path = "D:/桌面/user.csv";
        adminService.CustomerToCSV(path);

        FileSystemResource resource = new FileSystemResource(path);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=user.csv")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    @PostMapping("/card/add")
    @Operation(summary = "银行卡添加")
    public Result addCard(@RequestParam String pass, @RequestParam String pid, @RequestParam BigDecimal openMoney) {
        List<Cardinfo> list = adminService.addCard(pass, pid, openMoney);
        if(list == null || list.isEmpty()) return Result.error("500", "添加失败");
        return Result.success(list);
    }

    @GetMapping("/card/getList")
    @Operation(
            summary = "银行卡列表查询",
            parameters = {
                    @Parameter(name = "nums", description = "页码"),
                    @Parameter(name = "size", description = "每页数量")
            }
    )
    public Result getCardList(@RequestParam(defaultValue = "0") Integer nums, @RequestParam(defaultValue = "10") Integer size) {
        return Result.success(adminService.getCardList(nums, size));
    }

    @PutMapping("/card/update")
    @Operation(summary = "银行卡信息更新")
    public Result updateCard(@RequestBody CardUpdateDTO cardUpdateDTO) {
        // 验证卡号是否存在
        Cardinfo existingCard = cardinfoMapper.selectById(cardUpdateDTO.getCardID());
        if (existingCard == null) {
            return Result.error("500", "银行卡号不存在");
        }
        
        // 验证身份证号是否存在
        if (cardUpdateDTO.getPid() == null || cardUpdateDTO.getPid().isEmpty()) {
            return Result.error("500", "身份证号不能为空");
        }
        
        Userinfo user = userinfoMapper.selectOne(new QueryWrapper<Userinfo>().eq("PID", cardUpdateDTO.getPid()));
        if (user == null) {
            return Result.error("500", "身份证号对应的客户不存在");
        }
        
        // 验证卡号与身份证号是否匹配
        if (!existingCard.getCustomerID().equals(user.getCustomerID())) {
            return Result.error("500", "卡号与身份证号不匹配");
        }
        
        // 验证通过，创建Cardinfo对象进行更新
        Cardinfo updateCard = new Cardinfo();
        updateCard.setCardID(cardUpdateDTO.getCardID());
        if(cardUpdateDTO.getCurID() != null && !cardUpdateDTO.getCurID().isEmpty()) updateCard.setCurID(cardUpdateDTO.getCurID());
        updateCard.setIsReportLoss(cardUpdateDTO.getIsReportLoss());

        
        Boolean b = adminService.updateCard(updateCard);
        return b? Result.success(updateCard): Result.error("500", "更新失败");
    }

    @DeleteMapping("/card/delete")
    @Operation(summary = "银行卡删除")
    public Result deleteCard(@RequestBody cardIDAndPass cardIDAndPass) {
        Boolean b = adminService.deleteCard(cardIDAndPass.getCardID(), cardIDAndPass.getPassword());
        return b? Result.success(null): Result.error("500", "删除失败");
    }

    @GetMapping("/card/toCSV")
    @Operation(summary = "银行卡列表导出")
    public ResponseEntity<FileSystemResource> CardToCSV() throws IOException {
        String path = "D:/桌面/card.csv";
        adminService.CardToCSV(path);

        FileSystemResource resource = new FileSystemResource(path);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=card.csv")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }


    @GetMapping("/trade/getList")
    @Operation(summary = "交易列表查询",
        parameters = {
            @Parameter(name = "nums", description = "页码"),
            @Parameter(name = "size", description = "每页数量")
        }
    )
    public Result getTradeList(@RequestParam(defaultValue = "0") Integer nums, @RequestParam(defaultValue = "10") Integer size) {
        return Result.success(adminService.getTradeList(nums, size));
    }


    @DeleteMapping("/trade/delete")
    @Operation(summary = "交易删除",
        parameters = {
            @Parameter(name = "tradeID", description = "交易ID")
        }
    )
    public Result deleteTrade(Integer tradeID) {
        Boolean b = adminService.deleteTrade(tradeID);
        return b? Result.success(null): Result.error("500", "删除失败");
    }

    @GetMapping("/trade/toCSV")
    @Operation(summary = "交易列表导出")
    public ResponseEntity<FileSystemResource> TradeToCSV() throws IOException {
        String path = "D:/桌面/trade.csv";
        adminService.TradeToCSV(path);

        FileSystemResource resource = new FileSystemResource(path);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=trade.csv")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    @PostMapping("/deposit/add")
    @Operation(summary = "存款添加",
        parameters = {
            @Parameter(name = "SavingName", description = "存款类名"),
            @Parameter(name = "Descrip", description = "备注")
        }
    )
    public Result addDeposit(String SavingName, String Descrip) {
        Deposit deposit = new Deposit();
        deposit.setSavingName(SavingName);
        deposit.setDescrip(Descrip);

        Deposit newDeposit = adminService.addDeposit(deposit);

        if (newDeposit != null) {
            return Result.success(newDeposit);
        } else {
            return Result.error("400", "存款类型名称已存在，无法添加。");
        }
    }

    @GetMapping("/deposit/getList")
    @Operation(summary = "存款列表查询",
        parameters = {
            @Parameter(name = "nums", description = "页码"),
            @Parameter(name = "size", description = "每页数量")
        }
    )
    public Result getDepositList(@RequestParam(defaultValue = "1") Integer nums,@RequestParam(defaultValue = "10") Integer size) {
        return Result.success(adminService.getDepositList(nums, size));
    }

    @PutMapping("/deposit/update")
    @Operation(summary = "存款信息更新",
            parameters = {
                @Parameter(name = "savingID", description = "存款ID(必填)"),
                @Parameter(name = "savingName", description = "存款名称"),
                @Parameter(name = "descrip", description = "存款描述"),
            }
    )
    public Result updateDeposit(Long savingID, String savingName, String descrip) {
        Deposit deposit = new Deposit();
        deposit.setSavingID(savingID);
        deposit.setSavingName(savingName);
        deposit.setDescrip(descrip);

        return Result.success(adminService.updateDeposit(deposit));
    }

    @DeleteMapping("/deposit/delete")
    @Operation(summary = "存款删除",
        parameters = {
            @Parameter(name = "savingID", description = "存款ID")
        }
    )
    public Result deleteDeposit(Long savingID) {
        return Result.success(adminService.deleteDeposit(savingID));
    }

    @GetMapping("/deposit/toCSV")
    @Operation(summary = "存款列表导出")
    public ResponseEntity<FileSystemResource> DepositToCSV() throws IOException {
        String path = "D:/桌面/deposit.csv";
        adminService.DepositToCSV(path);
        FileSystemResource resource = new FileSystemResource(path);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=deposit.csv")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
}
